<script>
import {
  defineComponent,
  reactive,
  toRefs,
  ref,
  nextTick,
  onMounted,
  onUnmounted
} from 'vue'
import flvJs from 'flv.js'
import {
  apiGetRtspUrl
} from '../api/preview.js'

export default defineComponent({
  name: 'PreviewVideo',
  setup() {
    const state = reactive({
      player: null,
      rtspUrl: 'http://xxx'
    })

    const refPlayer = ref(null)

    const initUrl = () => {
      apiGetRtspUrl().then(res => {
        console.log(res)
      })
    }

    onMounted(() => {
      if(flvJs.isSupported()) {
        state.player = flvJs.createPlayer({
          type: 'flv',
          isLive: true,
          url: state.rtspUrl
        })

        state.player.on('error', (e) => {
          console.log(e)
        })

        nextTick(() => {
          state.player.attachMediaElement(refPlayer.value)
          try {
            state.player.load()
            state.player.play()
          } catch (e) {
            console.log(e)
          }
        })
      }
    })

    onUnmounted(() => {
      state.player.destroy()
    })

    return {
      ...toRefs(state),
      refPlayer
    }
  }
})
</script>

<template>
  <div class="component-preview-video-container">
    <video ref="refPlayer" class="videoBox" muted autoplay :controls="false" />
  </div>
</template>

<style lang="scss">
.component-preview-video-container {

}
</style>
